//
//  USAskDetailViewController.m
//  us
//
//  Created by karry on 2025/4/28.
//

#import "USAskDetailViewController.h"
#import "USAskEditViewController.h"
#import "USTalkDetailHeadView.h"
#import "USCommentInputToolView.h"
#import "USTalkAnswerCell.h"
#import "USCommentCell.h"
#import "USCommentModel.h"
@interface USAskDetailViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) USTalkDetailHeadView *headView;

@property (nonatomic, strong) UIButton *titleBtn;
@property (nonatomic, strong) UIButton *commitBtn;
@property (nonatomic, strong) USCommentInputToolView *commentTool;
@property (nonatomic, strong) NSMutableArray <USCommentModel *>*commentList;

@end

@implementation USAskDetailViewController


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    
    // 注册键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self setupView];
    
    if (self.dailyTalkId.length > 0) {
        @weakify(self)
        [self getTalkDetailWithDetailID:self.dailyTalkId success:^{
            @strongify(self)
            [self reloadHead];
            [self getCommentList];
        }];
     }else if (self.talkModel.dailyTalkId.length == 0) {
        @weakify(self)
        [self getTodayTalkSuccess:^{
            @strongify(self)
            [self reloadHead];
            [self getCommentList];
        }];
    }else{
        [self getCommentList];
    }
    
 
}

- (void)setupView{
    
    self.view.backgroundColor = [UIColor jk_colorWithHex:0xF3F4EF];
    
    [self.titleBtn setTitle:[NSString stringWithFormat:@"Q%li",self.talkModel.seq] forState:0];
    [self.titleBtn sizeToFit];
    self.navigationItem.titleView = self.titleBtn;

    self.us_tableView.delegate = self;
    self.us_tableView.dataSource = self;
    [self.us_tableView registerClass:[USTalkAnswerCell class] forCellReuseIdentifier:@"USTalkAnswerCell"];
    [self.us_tableView registerClass:[USCommentCell class] forCellReuseIdentifier:@"USCommentCell"];

    
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(cancelRes)];
    [self.us_tableView addGestureRecognizer:recognizer];
 
    
    [self.view addSubview:self.commitBtn];
    self.commitBtn.layer.cornerRadius = 23;
    [self.commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-24);
        make.bottom.mas_equalTo(self.view.mas_safeAreaLayoutGuideBottom).mas_offset(-12);
        make.width.height.mas_equalTo(46);
    }];
    
    [self.view addSubview:self.commentTool];
 
    @weakify(self);
    [RACObserve(self, talkModel.completionStatus) subscribeNext:^(NSNumber *state) {
        @strongify(self);
        self.commitBtn.hidden = state.integerValue == 0;
     }];
 
}

- (void)reloadHead {
    [self.titleBtn setTitle:[NSString stringWithFormat:@"Q%li",self.talkModel.seq] forState:0];

    self.headView.contentLab.text = self.talkModel.talkTitle;
        
    NSString *dayStr = [NSDateFormatter localizedStringFromDate:[NSDate dateWithTimeIntervalSince1970:self.talkModel.gmtCreate] dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];
    NSString *text = [NSString stringWithFormat:@"#第%li个问题 %@",self.talkModel.seq,dayStr];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
    NSRange seqRange = [text rangeOfString:[NSString stringWithFormat:@"%ld",self.talkModel.seq]];
    NSRange dayRange = [text rangeOfString:dayStr];
    [attributedString addAttribute:NSForegroundColorAttributeName value:UIColor.systemRedColor range:seqRange];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor jk_colorWithHex:0x212121 andAlpha:0.2] range:dayRange];
    self.headView.numLab.attributedText = attributedString;
}

- (void)reloadCharacter {
    if (self.commentList.count >= 2) {
        USCommentModel *model = self.commentList.firstObject;
        if ([model.userId isEqualToString:USUser.user.userId] && model.dailyTalkCommentId.length > 0) {
            self.headView.left_c_v.alpha = 1;
        }else{
            self.headView.left_c_v.alpha = 0.5;
        }
        
        USCommentModel *model1 = self.commentList[1];
        if (![model1.userId isEqualToString:USUser.user.userId] && model1.dailyTalkCommentId.length > 0) {
            self.headView.right_c_v.alpha = 1;
        }else{
            self.headView.right_c_v.alpha = 0.5;
        }
    }
 }
 
- (void)cancelRes {
    [self.commentTool.textField resignFirstResponder];
}

- (void)getTalkDetailWithDetailID:(NSString *)detailID success:(void(^)(void))success {
    [[EMNetWork shareManager] em_post:API_DailyTalkDetail
                               params:@{@"dailyTalkId":detailID?:@""}
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
        
        if (!api.success) {
            return;
        }
        USTalkModel *model = [USTalkModel mj_objectWithKeyValues:api.data[@"dailyTalk"]];
        self.talkModel = model;
        
        success();
    } fail:^{
        
        
    }];
}

- (void)getTodayTalkSuccess:(void(^)(void))success {
    [[EMNetWork shareManager] em_post:API_DailyTalkTodayDetail
                               params:nil
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
        
        if (!api.success) {
            return;
        }
        USTalkModel *model = [USTalkModel mj_objectWithKeyValues:api.data[@"dailyTalk"]];
        self.talkModel = model;
        
        success();
    } fail:^{
        
        
    }];
}

-(void)getCommentList {
    [[EMNetWork shareManager] em_post:API_DailyTalkCommentList
                               params:@{@"dailyTalkId":self.talkModel.dailyTalkId}
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
        
        if (!api.success) {
            return;
        }
        
        NSArray *list = [USCommentModel mj_objectArrayWithKeyValuesArray:api.data[@"dailyTalkCommentList"]];
        self.displayEmptySet = NO;

        // 保证有2条数据，并且自己在第一条
        NSMutableArray *arr = [NSMutableArray arrayWithArray:list];
        if (arr.count == 0) {
            USCommentModel *myModel = [USCommentModel new];
            myModel.userId = USUser.user.userId;
            
            USCommentModel *relModel = [USCommentModel new];
            relModel.userId = USUser.user.relUser.userId;
            relModel.noCompletion = YES;
            
            [arr addObject:myModel];
            [arr addObject:relModel];
            
        }else if (arr.count == 1) {
            USCommentModel *model = arr.firstObject;
            if ([model.userId isEqualToString:USUser.user.userId]) {
                USCommentModel *relModel = [USCommentModel new];
                relModel.userId = USUser.user.relUser.userId;
                
                [arr addObject:relModel];
            }else {
                USCommentModel *myModel = [USCommentModel new];
                myModel.userId = USUser.user.userId;
                
                model.noCompletion = YES;
                [arr insertObject:myModel atIndex:0];
            }
           
        }else {
            USCommentModel *model = arr.firstObject;
            if (![model.userId isEqualToString:USUser.user.userId]) {
                [arr exchangeObjectAtIndex:0 withObjectAtIndex:1];
            }
        }
        
        [self.commentList addObjectsFromArray:arr];
        
        [self reloadCharacter];
        
        [self.us_tableView reloadData];
        
        [self loadingSuccess];

    } fail:^{
        
        
    }];
}


/// 添加回答
/// - Parameters:
///   - content: 内容
- (void)sendComment:(NSString *)content{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:@{@"dailyTalkId":self.talkModel.dailyTalkId,@"content":content}];
    
    @weakify(self)
    [[EMNetWork shareManager] em_post:API_DailyTalkCommentAdd
                               params:params
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
        @strongify(self)
        if (!api.success) {
            return;
        }
        
        //最后插入数据
        USCommentModel *model = [USCommentModel new];
        model.userId = USUser.user.userId;
        model.content = content;
        model.gmtCreate = [[NSDate date] timeIntervalSince1970];
        
        [self.commentList addObject:model];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.commentList.count - 1 inSection:0];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.us_tableView beginUpdates];
            [self.us_tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            [self.us_tableView endUpdates];
            
            [self.us_tableView layoutIfNeeded];
        });
        
    } fail:^{
        
        
    }];
}

- (void)commentAction{
    [USFeedbackTool impactSoft];

    self.commentTool.hidden = NO;
    [self.commentTool.textField becomeFirstResponder];
}
- (void)editAnswerAction {
    [USFeedbackTool impactSoft];
    [self cancelRes];
    
    USAskEditViewController *vc = [[USAskEditViewController alloc]init];
    vc.commentList = self.commentList;
    vc.talkModel = self.talkModel;
    vc.commentModel = self.commentList.firstObject;
    @weakify(self)
    vc.didCommentBlock = ^{
     @strongify(self)
   
        self.headView.left_c_v.alpha = 1;

        if (self.commentList.count > 1) {
            if ( self.commentList[1].dailyTalkCommentId.length > 0) {
                self.commentList[1].noCompletion = NO;//双方都回答了
                self.talkModel.completionStatus = 1;
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.us_tableView reloadData];
        });
    };
    [self.navigationController presentViewController:[[DTNavigationController alloc]initWithRootViewController:vc] animated:YES completion:nil];
}
#pragma mark - 提醒Ta
- (void)remindAction {
 
    NSString *action_title = [NSString stringWithFormat:@"%@提醒你回答问题",USUser.user.nickname];
    NSDictionary *ext = @{@"action_id":self.talkModel.dailyTalkId,
                          @"action_title":action_title,
                          @"action_content":self.talkModel.talkTitle};
    
    [USIMCmdCustomManager imSendCmdWithAction:USIMCmdAction_TalkNotic andExt:ext];

    [USIMCmdCustomManager imSendCustomWithEvent:USIMCmdAction_TalkNotic andCustomExt:ext];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:@(USNoticeType_Talk) forKey:@"type"];
    [param setValue:self.talkModel.dailyTalkId?:@"" forKey:@"pkId"];
    [param setValue:@"提醒你回答问题" forKey:@"content"];
    [param setValue:USUser.user.relUser.userId forKey:@"userId"];
    [param setValue:@(1) forKey:@"shareSpaceFlag"];

    [[EMNetWork shareManager] em_post:NoticeAdd
                               params:param
                                  hud:nil
                            showError:NO
                              success:^(EMApiModel *api) {
 
    } fail:^{
        
        
    }];
}

- (UIButton *)titleBtn{
    if (!_titleBtn) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        _titleBtn = button;
        
        UIButtonConfiguration *config = [UIButtonConfiguration plainButtonConfiguration];
        config.contentInsets = NSDirectionalEdgeInsetsMake(0, 0, 0, 0);
        config.imagePadding = 6; // 图片和文字的间距
        config.titleAlignment = UIButtonConfigurationTitleAlignmentCenter; // 文字居中
        button.titleLabel.font = [UIFont systemFontOfSize:17 weight:UIFontWeightSemibold];
        button.configuration = config;
        [button setImage:[UIImage imageNamed:@"ic_love_red"] forState:UIControlStateNormal];
    }
    return _titleBtn;
}
- (USTalkDetailHeadView *)headView {
    if (_headView == nil) {
        _headView = [USTalkDetailHeadView jk_loadInstanceFromNib];
        self.headView = _headView;
        _headView.left_c_v.character = [USUser user].character;
        _headView.right_c_v.character = [USUser user].relCharacter;
        _headView.contentLab.text = self.talkModel.talkTitle;
        
        _headView.backgroundColor = [UIColor jk_colorWithHex:0xF3F4EF];

        NSString *dayStr = [NSDateFormatter localizedStringFromDate:[NSDate dateWithTimeIntervalSince1970:self.talkModel.gmtCreate] dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];
        NSString *text = [NSString stringWithFormat:@"#第%li个问题 %@",self.talkModel.seq,dayStr];
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
        NSRange seqRange = [text rangeOfString:[NSString stringWithFormat:@"%ld",self.talkModel.seq]];
        NSRange dayRange = [text rangeOfString:dayStr];
        [attributedString addAttribute:NSForegroundColorAttributeName value:UIColor.systemRedColor range:seqRange];
        [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor jk_colorWithHex:0x212121 andAlpha:0.2] range:dayRange];
        _headView.numLab.attributedText = attributedString;
        
    }
    return _headView;
}
 
- (UIButton *)commitBtn{
    if (!_commitBtn) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        _commitBtn = button;
        button.backgroundColor = UIColor.blackColor;
        [button setImage:[UIImage imageNamed:@"comment"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(commentAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _commitBtn;
}

- (USCommentInputToolView *)commentTool {
    if (_commentTool == nil) {
        _commentTool = [[USCommentInputToolView alloc]initWithFrame:CGRectMake(0, self.view.bounds.size.height, self.view.bounds.size.width, 74)];
        _commentTool.hidden = YES;
        @weakify(self)
        _commentTool.onSend = ^(NSString *text) {
            @strongify(self)
            NSLog(@"发送内容: %@", text);
            [self.commentTool.textField resignFirstResponder];
            
            NSString *content = self.commentTool.textField.text?:@"";
            
            self.commentTool.textField.text = @"";
            [self sendComment:content];

        };
        
    }
    return _commentTool;
}


 
- (void)keyboardWillShow:(NSNotification *)notification {

    NSDictionary *info = notification.userInfo;
    NSTimeInterval duration = [info[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    CGRect kbFrame = [info[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardHeight = kbFrame.size.height;
    
    CGFloat toolHeight = 74;
    [UIView animateWithDuration:duration animations:^{
        self.commentTool.frame = CGRectMake(0, self.view.bounds.size.height - keyboardHeight - toolHeight, self.view.bounds.size.width, toolHeight);
        self.commentTool.hidden = NO;
    }];
   
    UIEdgeInsets insets = UIEdgeInsetsMake(0, 0, keyboardHeight + 74, 0);
    self.us_tableView.contentInset = insets;
    self.us_tableView.scrollIndicatorInsets = insets;
    [self.us_tableView jk_scrollToBottomAnimated:YES];

}

- (void)keyboardWillHide:(NSNotification *)notification {

    NSDictionary *info = notification.userInfo;
    NSTimeInterval duration = [info[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duration animations:^{
        self.commentTool.frame = CGRectMake(0, self.view.bounds.size.height, self.view.bounds.size.width, 74);
    } completion:^(BOOL finished) {
        self.commentTool.hidden = YES;
    }];
    
    UIEdgeInsets insets = UIEdgeInsetsZero;
    self.us_tableView.contentInset = insets;
    self.us_tableView.scrollIndicatorInsets = insets;
}

- (NSMutableArray <USCommentModel *>*)commentList {
    if (_commentList == nil) {
        _commentList = [NSMutableArray array];
    }
    return _commentList;
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.commentList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < 2) {
        USTalkAnswerCell *cell = [tableView dequeueReusableCellWithIdentifier:@"USTalkAnswerCell" forIndexPath:indexPath];
 
        USCommentModel *model = self.commentList[indexPath.row];
        
        @weakify(self)
        cell.answerBlock = ^{
         @strongify(self)
            [self editAnswerAction];
       
        };
        cell.remindBlock = ^{
            NSLog(@"点击提醒");
            @strongify(self)
            [self remindAction];
        };
        cell.editAnswerBlock = ^{
          @strongify(self)
            [self editAnswerAction];
 
        };
        cell.model = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else {
        USCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"USCommentCell" forIndexPath:indexPath];

        USCommentModel *model = self.commentList[indexPath.row];
        
        cell.model = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
 
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 200;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return self.headView;
}
 

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 60;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}
@end
